#include "ThreadPool.h"

ThreadPool::ThreadPool() {
    min_num = 30;
    max_num = 50;
    max_queue_size = 10000; // 设置任务队列最大容量
    running = true;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&conn, NULL);
    sem_init(&sem, 0, 0);
    CreateIdleThread();
}

ThreadPool::~ThreadPool() {
    Stop(); // 停止线程池
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&conn);
    sem_destroy(&sem);
}

void ThreadPool::Stop() {
    running = false;
    pthread_cond_broadcast(&conn); // 唤醒所有等待的线程
    // 等待所有线程退出（可以通过其他机制实现）
}

void ThreadPool::CreateIdleThread() {
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < min_num; i++) {
        pthread_t thread_id;
        pthread_create(&thread_id, NULL, pthread_handle, this);
        idle_thread.push_back(thread_id);
    }
    pthread_mutex_unlock(&mutex);
}

void ThreadPool::AddTask(BaseTask* task) {
    pthread_mutex_lock(&mutex);
    while (task_queue.size() >= max_queue_size) {
        cout << "任务一点多" << endl;
        pthread_cond_wait(&conn, &mutex); // 队列满时等待
    }
    cout << "有新任务" << endl;
    task_queue.push(task);
    pthread_cond_signal(&conn);
    pthread_mutex_unlock(&mutex);
}

void ThreadPool::IdleToBusy(pthread_t thread_id) {
    auto it = std::find(idle_thread.begin(), idle_thread.end(), thread_id);
    if (it != idle_thread.end()) {
        idle_thread.erase(it);
        busy_thread.push_back(thread_id);
    }
}

void ThreadPool::BusyToIdle(pthread_t thread_id) {
    auto it = std::find(busy_thread.begin(), busy_thread.end(), thread_id);
    if (it != busy_thread.end()) {
        busy_thread.erase(it);
        idle_thread.push_back(thread_id);
    }
}

void* ThreadPool::pthread_handle(void* arg) {
    ThreadPool* pool = (ThreadPool*)arg;
    pthread_t self = pthread_self();

    while (pool->running) {
        BaseTask* task = nullptr;

        pthread_mutex_lock(&pool->mutex);
        while (pool->task_queue.empty() && pool->running) {
            pthread_cond_wait(&pool->conn, &pool->mutex);
        }

        if (!pool->running) {
            pthread_mutex_unlock(&pool->mutex);
            break;
        }

        if (!pool->task_queue.empty()) {
            pool->IdleToBusy(self);
            task = pool->task_queue.front();
            pool->task_queue.pop();
        }
        pthread_mutex_unlock(&pool->mutex);

        if (task) {
            task->working();
        }
        cout << "执行完成" << endl;
        pthread_mutex_lock(&pool->mutex);
        pool->BusyToIdle(self);
        pthread_mutex_unlock(&pool->mutex);
    }
    return nullptr;
}